﻿/*
 * @author: wizardc
 */

using System;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Serialization;

namespace Dou.UI
{
    /// <summary>
    /// 基于 TextMeshPro 实现的输入框
    /// </summary>
    [ExecuteInEditMode]
    public class DTMP_InputField : TMP_InputField
    {
        [Serializable]
        public class KeyboardOpeningEvent : UnityEvent<float> {}
        
        [Serializable]
        public class KeyboardClosedEvent : UnityEvent {}
        
        public OnChangeEvent onInputChanged;
        public SubmitEvent onInputStart;
        public SubmitEvent onInputEnd;
        
        public KeyboardOpeningEvent onKeyboardOpening;
        public KeyboardClosedEvent onKeyboardClosed;
        
        private bool _inputChanged = false;

        private float _lastKeyboardHeight = 0;

        protected override void Awake()
        {
            base.Awake();
            onValueChanged.AddListener(ValueChangedHandler);
            onSelect.AddListener(SelectHandler);
            onDeselect.AddListener(DeselectHandler);
        }

        private void ValueChangedHandler(string text)
        {
            _inputChanged = true;
        }

        private void SelectHandler(string text)
        {
            onInputStart?.Invoke(text);
        }

        private void DeselectHandler(string text)
        {
            onInputEnd?.Invoke(text);
        }

        protected override void LateUpdate()
        {
            base.LateUpdate();
            if (_inputChanged)
            {
                _inputChanged = false;
                onInputChanged?.Invoke(text);
            }
            if (m_SoftKeyboard != null && m_SoftKeyboard.status == TouchScreenKeyboard.Status.Visible)
            {
                var height = UIUtil.GetKeyboardHeight();
                if (_lastKeyboardHeight != height)
                {
                    _lastKeyboardHeight = height;
                    onKeyboardOpening?.Invoke(_lastKeyboardHeight);
                }
            }
            else
            {
                if (_lastKeyboardHeight != 0)
                {
                    _lastKeyboardHeight = 0;
                    onKeyboardClosed?.Invoke();
                }
            }
        }
    }
}
